//
//  MainViewController.m
//  UCiEnabler
//
//  Created by Delio Brignoli on 21/07/08.
//  Copyright __MyCompanyName__ 2008. All rights reserved.
//

#include <AudioToolbox/AudioToolbox.h>
#import "UCiEnablerAppDelegate.h"
#import "IEnablerService.h"
#import "MainViewController.h"
#import "MainView.h"

@implementation MainViewController


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
	if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
		// Custom initialization
	}
	return self;
}

- (void)viewDidLoad {
	MainView *v = (MainView*)[self view];
	v.sectionTitles = [NSArray arrayWithObjects:@"UC Login",@"UC Internet Enabler",nil];
	table = (UITableView *)[v viewWithTag:333];

	[[IEnablerService sharedIEnablerService] addObserver:self forKeyPath:@"status"
												 options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld)
												 context:NULL];	
}

- (void)action:(id)sender {
	@synchronized(self) {
		//Start the update
		UCiEnablerAppDelegate *controller = (UCiEnablerAppDelegate *)[[UIApplication sharedApplication] delegate];
		[controller deduceIEnablerServiceAccess];
	}
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
	@synchronized(self) {
		if ([keyPath compare:@"status"] == 0) {
			IEnablerService *iEnablerService = (IEnablerService *)object;
			MainView *v = (MainView*)[self view];

			IEnablerStatus newStatus = (IEnablerStatus)[(NSNumber*)[change valueForKey:NSKeyValueChangeNewKey] intValue];

			if (newStatus == IEnablerServiceUpdating) {
				//Disable the switch until the update is done to avoid re-entrant calls
				[(UISwitch *)v.switchCell.view setEnabled:NO];
				//Update the status widget to a progress indicator

				UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
				activityIndicator.hidesWhenStopped = NO;
				[activityIndicator startAnimating];
				v.statusCell.view = activityIndicator;
				[activityIndicator release];
				
				v.statusCell.nameLabel.text = @"Updating";
				v.mode = MainViewUpdating;
				
				return;
			}

			if ( newStatus == IEnablerServiceAccessEnabled || newStatus == IEnablerServiceAccessDisabled ) {
				v.mode = MainViewShowSwitch;
				if ( [(UISwitch *)v.switchCell.view isOn] != (newStatus == IEnablerServiceAccessEnabled) ) {
					AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
					[(UISwitch *)v.switchCell.view setOn:(newStatus == IEnablerServiceAccessEnabled)?YES:NO animated:YES];
				}
				[(UISwitch *)v.switchCell.view setEnabled:YES];
				v.switchCell.contentView.alpha = 1.0;
				v.statusCell.view = nil;
				v.statusCell.nameLabel.text = @"Reachable";
			} else {
				UIButton* btn = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
				[btn setTitle:@"Retry" forState:UIControlStateNormal];
				btn.frame = CGRectMake(0.0, 0.0, 96, 27);
				[btn addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside];
				v.statusCell.view = btn;

				if (newStatus != IEnablerServiceNotReachable) {
					//v.statusCell.nameLabel.text = [[IEnablerService sharedIEnablerService] errorReason]; //@"Error";
					v.statusCell.nameLabel.text = @"Error";
				} else {
					//v.statusCell.nameLabel.text = [[IEnablerService sharedIEnablerService] errorReason]; //@"Unreachable";
					v.statusCell.nameLabel.text = @"Unreachable";
				}

				[btn release];
				v.mode = MainViewShowStatus;
				[(UISwitch *)v.switchCell.view setEnabled:NO];
				v.switchCell.contentView.alpha = 0.5;
			}

		}
	}
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {	
	// Return YES for supported orientations
	return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
	// Release anything that's not essential, such as cached data
}


- (void)dealloc {
	[super dealloc];
}


@end
